// pages/mallIndex/mallIndex.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		categories: [],
		page: 1,
		hasMore: true,
		goodsList: [],

		chooseMenu: null,
		goodsType: 'all',
		sortPrice: 0,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		this.onPullDownRefresh();
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {
		const menu = this.data.chooseMenu;
		if (menu) {
			this.loadCategories();
			this.loadGoodsList(1).finally(() => {
				wx.stopPullDownRefresh();
			});
		} else {
			this.loadCategories().then(() => {
				this.loadGoodsList(1).finally(() => {
					wx.stopPullDownRefresh();
				});
			});
		}
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {
		if (!this.data.hasMore) return;

		const page = this.data.page + 1;
		this.loadGoodsList(page);
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		const menu = this.data.chooseMenu,
			image = menu && menu.image ? menu.image.file_path : null;
		return {
			imageUrl: image,
			path: this.route
		}
	},

	// 加载分类信息
	loadCategories: function() {
		return wx.http.get('api/category/index').then((res) => {
			const menu = this.data.chooseMenu;
			const categories = res.data.data.list;
			this.setData({
				chooseMenu: menu === null ? categories[0] : menu,
				categories: categories
			});
			return categories;
		}, (err) => {
			console.warn("api/category/index", err)
		});
	},

	// 加载商城列表
	loadGoodsList: function(page) {
		const menu = this.data.chooseMenu,
			menuId = menu ? menu.category_id : null;

		return wx.http.get('api/goods/lists', {
			page: page,
			sortType: this.data.goodsType,
			sortPrice: this.data.sortPrice,
			category_id: menuId,
			search: '',
			course_id: '',
		}).then((res) => {
			res = res.data.data.list;
			const hasMore = res.data.length >= res.per_page;
			const goodsList = page > 1 ? this.data.goodsList.concat(res.data) : res.data;
			this.setData({
				page: page,
				hasMore: hasMore,
				goodsList: goodsList,
			});
			return res.data;
		}, (err) => {
			console.warn("api/goods/lists", err)
		});
	},

	// 左侧分类切换
	goodsMenuTap: function(e) {
		const index = e.currentTarget.dataset.index;
		const menu = this.data.categories[index];
		this.data.chooseMenu = menu;
		this.setData({
			chooseMenu: menu
		});
		this.loadGoodsList(1);
	},

	// 右侧筛选
	filterTap: function(e) {
		const goodsType = e.currentTarget.dataset.state;
		const data = {goodsType: goodsType};

		// 处理价格排序
		if (goodsType === "price" && this.data.goodsType === "price") {
			const sortPrice = this.data.sortPrice ? 0 : 1;
			data.sortPrice = sortPrice;
			this.data.sortPrice = sortPrice;
		}

		this.data.goodsType = goodsType;
		this.setData(data);
		this.loadGoodsList(1);
	},
});
